#include <Mouse.h>
#include <Keyboard.h>
#define ER "ER\n"
#define OK "OK\n"
// 使用Serial1从蓝牙或电脑处读取到的命令
String inputString = "";  // 用来存储接收到的指令
String serialOneString = "";  // 用来存储接收到的指令
//点击键盘
bool pressKey(String key) {
  // 控制键
  if (key == "CTRL") { Keyboard.press(KEY_LEFT_CTRL); return true; }
  else if (key == "SHIFT") { Keyboard.press(KEY_LEFT_SHIFT); return true; }
  else if (key == "ALT") { Keyboard.press(KEY_LEFT_ALT); return true; }
  else if (key == "GUI" || key == "WIN") { Keyboard.press(KEY_LEFT_GUI); return true; }
  // 功能键 F1~F12
  else if (key == "F1") { Keyboard.press(KEY_F1); return true; }
  else if (key == "F2") { Keyboard.press(KEY_F2); return true; }
  else if (key == "F3") { Keyboard.press(KEY_F3); return true; }
  else if (key == "F4") { Keyboard.press(KEY_F4); return true; }
  else if (key == "F5") { Keyboard.press(KEY_F5); return true; }
  else if (key == "F6") { Keyboard.press(KEY_F6); return true; }
  else if (key == "F7") { Keyboard.press(KEY_F7); return true; }
  else if (key == "F8") { Keyboard.press(KEY_F8); return true; }
  else if (key == "F9") { Keyboard.press(KEY_F9); return true; }
  else if (key == "F10") { Keyboard.press(KEY_F10); return true; }
  else if (key == "F11") { Keyboard.press(KEY_F11); return true; }
  else if (key == "F12") { Keyboard.press(KEY_F12); return true; }
  // 字母 A-Z
  else if (key.length() == 1 && isAlpha(key.charAt(0))) {
    return Keyboard.press(key.charAt(0));
  }
  // 数字 0-9
  else if (key.length() == 1 && key.charAt(0) >= '0' && key.charAt(0) <= '9') {
    Keyboard.press(key.charAt(0));
    return true;
  }
  // 方向键
  else if (key == "UP") { Keyboard.press(KEY_UP_ARROW); return true; }
  else if (key == "DOWN") { Keyboard.press(KEY_DOWN_ARROW); return true; }
  else if (key == "LEFT") { Keyboard.press(KEY_LEFT_ARROW); return true; }
  else if (key == "RIGHT") { Keyboard.press(KEY_RIGHT_ARROW); return true; }

  // 特殊功能键
  else if (key == "ENTER") { Keyboard.press(KEY_RETURN); return true; }
  else if (key == "TAB") { Keyboard.press(KEY_TAB); return true; }
  else if (key == "ESC") { Keyboard.press(KEY_ESC); return true; }
  else if (key == "BACKSPACE") { Keyboard.press(KEY_BACKSPACE); return true; }
  else if (key == "DELETE") { Keyboard.press(KEY_DELETE); return true; }
  else if (key == "SPACE") { Keyboard.press(' '); return true; }
  else if (key == "HOME") { Keyboard.press(KEY_HOME); return true; }
  else if (key == "END") { Keyboard.press(KEY_END); return true; }
  else if (key == "PAGEUP") { Keyboard.press(KEY_PAGE_UP); return true; }
  else if (key == "PAGEDOWN") { Keyboard.press(KEY_PAGE_DOWN); return true; }
  else if (key == "INSERT") { Keyboard.press(KEY_INSERT); return true; }
  // 忽略逗号
  else if (key == ",") {
    return false;  // 逗号本身不算按键
  }
  // 未知键
  return false;
}

void onKey(String command){
  if (!command.startsWith("K:")) {
    Serial.println(ER);
    return;
  }
  String keysStr = command.substring(2);  // Remove "K:"
  keysStr.trim();
  int start = 0;
  while (start < keysStr.length()) {
    int end = keysStr.indexOf(',', start);
    if (end == -1) end = keysStr.length();
    String key = keysStr.substring(start, end);
    key.trim();
    pressKey(key);
    start = end + 1;
  }
  delay(50);  // Hold keys for 100ms
  Keyboard.releaseAll();
  Serial.println(OK);
}

void onMoveMouse(String command){
  if (!command.startsWith("M:")){
     Serial.println(ER);
     return;
  }
  //提取内容 "x,y,z,k"
  String params = command.substring(2);
  params.trim();
  int firstComma = params.indexOf(',');
  int secondComma = params.indexOf(',', firstComma + 1);
  int thirdComma = params.indexOf(',', secondComma + 1);

  if (firstComma == -1 || secondComma == -1 || thirdComma == -1) {
    Serial.println(ER);
    return;
  }
  int x = params.substring(0, firstComma).toInt();
  int y = params.substring(firstComma + 1, secondComma).toInt();
  int z = params.substring(secondComma + 1, thirdComma).toInt();
  int k = params.substring(thirdComma + 1).toInt();
  if (k <= 0) {
    Serial.println(ER);
    return;
  }
  int remainingX = x;
  int remainingY = y;
  while (remainingX != 0 || remainingY != 0) {
    int stepX = constrain(remainingX, -k, k);
    int stepY = constrain(remainingY, -k, k);
    Mouse.move(stepX, stepY, 0);  // 第三个参数是滚轮，可以设为0
    delay(z);
    remainingX -= stepX;
    remainingY -= stepY;
  }
  Serial.println(OK);
}

/**
特殊指令任务
*/
void onTask(String command){
  if (!command.startsWith("T:")) {
    Serial.println(ER);
    return;
  }
  int task_status = -1;
  int value = command.substring(2).toInt();
  switch (value) {
    case 2:
      Mouse.click(MOUSE_MIDDLE);
      break;
    case 3:
      Mouse.click(MOUSE_RIGHT);
      break;
    case 4:
      Mouse.click(MOUSE_LEFT);
      break;
    default:
      task_status = 0;
      break;
  }
  if(task_status==0){
      Serial.println(ER);
  }else{
      Serial.println(OK);
  }
}

void setup() {
  // Serial 连电脑端，只写不读
  Serial.begin(115200);
  // Serial1 读写
  Serial1.begin(115200);
}

void loop() {
  // 检查是否有数据从串口发送过来
  if (Serial.available() > 0) {
    // 逐个字符读取串口输入
    char incomingByte = Serial.read();
    // 如果是换行符\n，表示一条完整指令接收完毕
    if (incomingByte == '\n') {
      //判断是否以"M:"开头，以"M:"开头是移动命令
      if (inputString.startsWith("M:")) {
        onMoveMouse(inputString);
      //判断是否以"K:"开头，以"K:"开头是按钮点击命令
      }else if(inputString.startsWith("K:")){
        onKey(inputString);
      //判断是否以"T:"开头，以"T:"开头是特殊命令
      }else if(inputString.startsWith("T:")){
        onTask(inputString);
      }else{
        Serial.println(ER);
      }
      // 清空接收缓冲区准备接收下一条指令
      inputString = "";
    } else {
      // 将接收到的字符添加到指令字符串中
      inputString += incomingByte;
    }
  }
  if (Serial1.available() > 0) {
    // 逐个字符读取串口输入
    char incomingByte1 = Serial1.read();
    // 如果是换行符\n，表示一条完整指令接收完毕
    if (incomingByte1 == '\n') {
      if (serialOneString.endsWith("\r")) {
        serialOneString.remove(serialOneString.length() - 1);
      }
      Serial1.println(serialOneString);
      // 清空接收缓冲区准备接收下一条指令
      serialOneString = "";
    } else {
      // 将接收到的字符添加到指令字符串中
      serialOneString += incomingByte1;
    }
  }
}